extern crate winres;
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::Command;

fn get_git_version() -> String {
    let version = env::var("CARGO_PKG_VERSION").unwrap().to_string();

    // run [dotnet gitversion /showvariable InformationalVersion] get gitversion version
    let child = Command::new("dotnet")
        .args(&["gitversion", "/output", "json"])
        .output();
    match child {
        Ok(child) => {
            let buf = String::from_utf8(child.stdout).expect("failed to read stdout");
            return buf;
        }
        Err(err) => {
            eprintln!("`gitversion` err: {}", err);
            return version;
        }
    }
}

fn main() {
    // windows resource
    let res = winres::WindowsResource::new();
    match res.compile() {
        Err(e) => {
            write!(std::io::stderr(), "{}", e).unwrap();
            std::process::exit(1);
        }
        Ok(_) => {}
    }

    // gitversion
    let version = get_git_version();
    let mut f = File::create(Path::new(&env::var("OUT_DIR").unwrap()).join("GITVERSION")).unwrap();
    f.write_all(version.to_string().trim().as_bytes()).unwrap();
}
